<template>
	<view>
		<z-paging ref="paging" v-model="dataList" @query="queryList">
			<template #top>
				<tn-navbar> 进出查询</tn-navbar>
				<tn-input v-model="inputValue" placeholder="请输入车牌查询" @change="filterData">
					<template #suffix>
						<view class="tn-ml tn-mr" @click="filterData">
							<tn-icon name="search" color=" tn-gray_bg"></tn-icon>
						</view>
					</template>
				</tn-input>
				<view class="tn-shadow  ">
					<view class="tn-flex tn-mt-sm justify-end tn-pr-sm  tn-pb-sm ">
						<view class="tn-flex tn-blue_text" @click="openEditPopup"><tn-icon name="filter"></tn-icon>筛选</view>
					</view>
				</view>
			</template>

			<view class="tn-mt-lg tn-flex tn-flex-column ">
				<view v-for="(item, index) in dataList" :key="index" class="list-item tn-flex tn-flex-row  justify-between  tn-p-sm" @click="tnParamById('/pages/main/common/detail', JSON.stringify(item))">
					<view class="tn-flex">
						<view class="tn-flex tn-align-center justify-start">
							<tn-icon name="parking" color="tn-teal" size="60" />
						</view>
						<view class="tn-flex tn-flex-column tn-justify-center  tn-ml-sm">
							<view> <text>{{ item.numberPlate }}</text>
								<text class="tn-text-xs tn-gray_text tn-pl-xs">{{'('+item.newCarType+')'}} &nbsp;&nbsp;入:{{ item.newInReleaseType }} &nbsp;&nbsp;出:{{ item.newOutReleaseType }}</text>
							</view>
							<view class="tn-flex justify-between tn-mt-sm"></view>
							<text class="tn-gray_text" style="margin-left: -36px;">入:{{ item.newInTime }} &nbsp;&nbsp;出:{{ item.newOutTime }}</text>
						</view>
					</view>

					<view class="tn-flex tn-align-center  justify-end">
						<!-- <tn-icon name="right" size="30" color="tn-gray" /> -->
						<text :class="item.outTime==0?'tn-teal_text':'tn-red_text'" class="tn-text-lg">{{ item.outTime==0 ?'进':'出' }}</text>
					</view>
				</view>
			</view>
			<template #loadingMoreNoMore> </template>
		</z-paging>

		<tn-popup v-model="isPopupVisible" width="80%" top="230rpx" open-direction="top" :overlay="false" :radius="25">
			<view class="tn-shadow  tn-p-sm  tn-border  tn-border-bottom  tn-border-top tn-gray-disabled_border">
				<tn-form ref="formRef" :model="formData" label-position="top">
					<tn-form-item label="入场时间">
						<view class="tn-flex justify-between">
							<view>
								<tn-input @focus="openPickerDate('minInTime')" :model-value="formData.minInTime" placeholder="入场时间>=">
                  <template #suffix>
                    <view class="tn-ml tn-mr" @click="cleanInputValue('minInTime')">
                      <tn-icon name="delete" color=" tn-gray_bg"></tn-icon>
                    </view>
                  </template>
                </tn-input>
							</view>-<view>
								<tn-input @focus="openPickerDate('maxInTime')" :model-value="formData.maxInTime" placeholder="入场时间<=">
                  <template #suffix>
                    <view class="tn-ml tn-mr" @click="cleanInputValue('maxInTime')">
                      <tn-icon name="delete" color=" tn-gray_bg"></tn-icon>
                    </view>
                  </template>
                </tn-input>
							</view>
						</view>
					</tn-form-item>
          <tn-form-item label="出场时间">
            <view class="tn-flex justify-between">
              <view>
                <tn-input @focus="openPickerDate('minOutTime')" :model-value="formData.minOutTime" placeholder="出场时间>=">
                  <template #suffix>
                    <view class="tn-ml tn-mr" @click="cleanInputValue('minOutTime')">
                      <tn-icon name="delete" color=" tn-gray_bg"></tn-icon>
                    </view>
                  </template>
                </tn-input>
              </view>-<view>
              <tn-input @focus="openPickerDate('maxOutTime')" :model-value="formData.maxOutTime" placeholder="出场时间<=">
                <template #suffix>
                  <view class="tn-ml tn-mr" @click="cleanInputValue('maxOutTime')">
                    <tn-icon name="delete" color=" tn-gray_bg"></tn-icon>
                  </view>
                </template>
              </tn-input>
            </view>
            </view>
          </tn-form-item>
					<tn-form-item label="进出场通道">
            <view class="tn-flex justify-between">
              <view>
                <tn-input @focus="openPicker('inCheckPointList')" :model-value="selectOptions.checkPointLabel[formData.inCheckPointId]" placeholder="请选择入场通道">
                  <template #suffix>
                    <view class="tn-ml tn-mr" @click="cleanInputValue('inCheckPointId')">
                      <tn-icon name="delete" color=" tn-gray_bg"></tn-icon>
                    </view>
                  </template>
                </tn-input>
              </view>
              <view>
                <tn-input @focus="openPicker('outCheckPointList')" :model-value="selectOptions.checkPointLabel[formData.outCheckPointId]" placeholder="请选择出场通道">
                  <template #suffix>
                    <view class="tn-ml tn-mr" @click="cleanInputValue('outCheckPointId')">
                      <tn-icon name="delete" color=" tn-gray_bg"></tn-icon>
                    </view>
                  </template>
                </tn-input>
              </view>
            </view>
					</tn-form-item>

          <tn-form-item label="进出场方式">
            <view class="tn-flex justify-between">
              <view>
                <tn-input @focus="openPicker('inReleaseTypeList')" :model-value="selectOptions.inReleaseTypeLabel[formData.inReleaseType]" placeholder="请选择入场方式">
                  <template #suffix>
                    <view class="tn-ml tn-mr" @click="cleanInputValue('inReleaseType')">
                      <tn-icon name="delete" color=" tn-gray_bg"></tn-icon>
                    </view>
                  </template>
                </tn-input>
              </view>
              <view>
                <tn-input @focus="openPicker('outReleaseTypeList')" :model-value="selectOptions.outReleaseTypeLabel[formData.outReleaseType]" placeholder="请选择出场方式">
                  <template #suffix>
                    <view class="tn-ml tn-mr" @click="cleanInputValue('outReleaseType')">
                      <tn-icon name="delete" color=" tn-gray_bg"></tn-icon>
                    </view>
                  </template>
                </tn-input>
              </view>
            </view>
          </tn-form-item>

          <tn-form-item label="车辆类型">
            <view class="tn-flex justify-between">
              <view>
                <tn-input @focus="openPicker('carTypeList')" :model-value="selectOptions.carTypeLabel[formData.carType]" placeholder="请选择车辆类型">
                  <template #suffix>
                    <view class="tn-ml tn-mr" @click="cleanInputValue('carType')">
                      <tn-icon name="delete" color=" tn-gray_bg"></tn-icon>
                    </view>
                  </template>
                </tn-input>
              </view>
              <view>
                <tn-input v-model="formData.homeGroup" placeholder="家庭组/一多位多车">
                  <template #suffix>
                    <view class="tn-ml tn-mr" @click="cleanInputValue('homeGroup')">
                      <tn-icon name="delete" color=" tn-gray_bg"></tn-icon>
                    </view>
                  </template>
                </tn-input>
              </view>
            </view>
          </tn-form-item>
				</tn-form>

				<view class="tn-mt tn-flex justify-evenly  ">
					<tn-button @click="closePopup" text-color="tn-white" bg-color="tn-grey_bg
">取消</tn-button>
					<tn-button @click="confirmEdit" text-color="tn-white" >确认</tn-button>
				</view>
			</view>


		</tn-popup>
		<!-- 时间选择器 -->
		<tn-date-time-picker v-model:open="openPickerDateVisible" mode="datetime" @confirm="confirmPickerDate" @close="closePickerDate" />
		<!-- 字典选择器 -->
		<tn-picker v-model:open="openPickerVisible" :data="pickerData" @confirm="confirmPicker" @close="closePicker" />
	</view>
</template>

<script setup lang="ts">
import {onMounted, type Ref, ref} from "vue";
	import { tnParamById } from "@/utils/tnUtil";
	import { onLoad } from "@dcloudio/uni-app";
	import CfCarParkUtil from "@/cfsheep/api/cfCarPark/park";
	import { parseTime, timeFn } from "@/cfsheep/util";
	import CfPayUtil from "@/cfsheep/api/pay/pay";
import { COUPON_TYPE  } from '@/utils/dict';
  import dayjs from "dayjs";
  import CfIOTUtil from "@/cfsheep/api/iot/iot"; // 引入字典
	const formData = ref({
		minInTime: null,
		maxInTime: null,
		minOutTime: null,
		maxOutTime: null,
    inCheckPointId:null,
    outCheckPointId:null,
    carType:null,
    inReleaseType:null,
    outReleaseType:null,
    homeGroup:null,
	});
	// 下拉筛选- 筛选索引 
	const isPopupVisible = ref(false);
	const openEditPopup = (value : any) => { 
		isPopupVisible.value = true;
	};

	const closePopup = () => {
		isPopupVisible.value = false;
	};
	const confirmEdit = () => {
		// 确认修改逻辑
		closePopup();
    queryList(1, 10);
	};


	// 日期时间筛选-选择器key
	const pickerDateKey = ref('');

	// 日期时间控制选择器的可见性
	const openPickerDateVisible = ref(false);

	// 打开日期时间选择器
	const openPickerDate = (type: any) => {
		pickerDateKey.value = type;
		openPickerDateVisible.value = true; // 显示选择器
	};

	// 关闭日期时间选择器
	const closePickerDate = () => {
		openPickerDateVisible.value = false; // 隐藏选择器
	};

	// 确认日期时间选择器的选择
	const confirmPickerDate = (value : any) => {
		formData.value[pickerDateKey.value] = value;
		closePickerDate(); // 关闭选择器
	};

//下拉框数据
const selectOptions = ref({
  dict: {
    inCheckPointList: [],
    outCheckPointList: [],
    carTypeList: [],
    //0-未放行/1-自动抬杆/2-人工抬杆/3-手机放行，断电断网时/4-扫码入场/5-异常放行
    inReleaseTypeList: [
      { label: "未放行", text: "未放行", value: 0 },
      { label: "自动抬杆", text: "自动抬杆", value: 1 },
      { label: "人工抬杆", text: "人工抬杆", value: 2 },
      { label: "手机放行", text: "手机放行", value: 3 },
      { label: "扫码入场", text: "扫码入场", value: 4 },
      { label: "异常放行", text: "异常放行", value: 5 }
    ],
    outReleaseTypeList: [
      { label: "未放行", text: "未放行", value: 0 },
      { label: "自动抬杆", text: "自动抬杆", value: 1 },
      { label: "人工抬杆", text: "人工抬杆", value: 2 },
      { label: "手机放行", text: "手机放行", value: 3 },
      { label: "扫码入场", text: "扫码入场", value: 4 },
      { label: "异常放行", text: "异常放行", value: 5 }
    ],
  },
  checkPointLabel: {},
  carTypeLabel: {},
  inReleaseTypeLabel: {0: '未放行', 1: '自动抬杆', 2: '人工抬杆', 3: '手机放行', 4: '扫码入场', 5: '异常放行'},
  outReleaseTypeLabel: {0: '未放行', 1: '自动抬杆', 2: '人工抬杆', 3: '手机放行', 4: '扫码入场', 5: '异常放行'},
});

// 选择器key
const pickerKey = ref('');
// 选择器数据
const pickerData = ref([]);

// 控制选择器的可见性
const openPickerVisible = ref(false);

// 打开选择器
const openPicker = (type:any)  => {
	pickerKey.value = type;
	pickerData.value = selectOptions.value.dict[type];
	openPickerVisible.value = true; // 显示选择器
};

// 关闭选择器
const closePicker = () => {
	openPickerVisible.value = false; // 隐藏选择器
};

const cleanInputValue = (valueType: string) => {
	formData.value[valueType] = null;
};

// 确认选择器的选择
const confirmPicker = (value: any) => {
  switch (pickerKey.value){
    case "inCheckPointList":
      formData.value.inCheckPointId = value;
      break;
    case "outCheckPointList":
      formData.value.outCheckPointId = value;
      break;
    case "inReleaseTypeList":
      formData.value.inReleaseType = value;
      break;
    case "outReleaseTypeList":
      formData.value.outReleaseType = value;
      break;
    case "carTypeList":
      formData.value.carType = value;
      break;
  }
	closePicker(); // 关闭选择器
};

	//============

	const inputValue = ref("");
	const carParkId = ref(0);
	const numberPlate = ref('');
	const carTypeList = ref([]);
	const paymentAgencyList: Ref<CfPaymentAgency[]> = ref([]);

	const filterData = (_numberPlate : string) => {
		if (_numberPlate.length >= 4 || _numberPlate === '') {
			numberPlate.value = _numberPlate;
			queryList(1, 10);
		} else {
			dataList.value = [];
			paging.value.complete(dataList.value);
		}
	};
	// z-paging 示例
	const paging = ref(null);
	// 数据列表
	const dataList: Ref<CfCarParkUseLog[]> = ref([]);

	const releaseTypeArr = [
		{ value: 0, label: '未放行' },
		{ value: 1, label: '自动抬杆' },
		{ value: 2, label: '人工抬杆' },
		{ value: 3, label: '手机放行' },
		{ value: 4, label: '扫码' },
		{ value: 5, label: '异常放行' },
	];

	/**
	* 拉取停车记录
	* @param pageNo
	* @param pageSize
	*/
	const queryList = async (pageNo : number, pageSize : number) => {
		let params = {
			page: pageNo,
			size: pageSize,
			carParkId: carParkId.value,
			numberPlate: numberPlate.value
		};
		if (numberPlate.value === '') {
			delete params.numberPlate;
		}
    if(formData.value.minInTime !== null){
      params.minInTime = dayjs(formData.value.minInTime).valueOf();
    }
    if(formData.value.maxInTime !== null){
      params.maxInTime = dayjs(formData.value.maxInTime).valueOf();
    }
    if(formData.value.minOutTime !== null){
      params.minOutTime = dayjs(formData.value.minOutTime).valueOf();
    }
    if(formData.value.maxOutTime !== null){
      params.maxOutTime = dayjs(formData.value.maxOutTime).valueOf();
    }
    if(formData.value.inCheckPointId !== null){
      params.inCheckPointId = formData.value.inCheckPointId;
    }
    if(formData.value.outCheckPointId !== null){
      params.outCheckPointId = formData.value.outCheckPointId;
    }
    if(formData.value.carType !== null){
      params.carType = formData.value.carType;
    }
    if(formData.value.inReleaseType !== null){
      params.inReleaseType = formData.value.inReleaseType;
    }
    if(formData.value.outReleaseType !== null){
      params.outReleaseType = formData.value.outReleaseType;
    }
    if(formData.value.homeGroup !== null){
      params.homeGroup = formData.value.homeGroup;
    }
		const _dataList = await CfCarParkUtil.getCarParkUseLogListByQuery(params);
		if (_dataList.code == 10002) {
			dataList.value = _dataList.data;
			for (const i of _dataList.data) {
				i.newCarType = getCarTypeName(i.carType) || '-';
				i.newInTime = parseTime(i.inTime, null) || '-';
				i.newOutTime = parseTime(i.outTime, null) || '-';
				i.newPayTime = parseTime(i.payTime, null) || '-';
				i.parkingDuration = (i.inTime && i.outTime) ? timeFn(Number(i.inTime), Number(i.outTime)) : '-';
				for (const j of releaseTypeArr) {
					if (i.inReleaseType == j.value) {
						i.newInReleaseType = j.label;
					}
					if (i.outReleaseType == j.value) {
						i.newOutReleaseType = j.label;
					}
				}
				for (const j of paymentAgencyList.value) {
					if (i.paymentAgencyShortName == j.paymentAgencyName) {
						i.paymentAgencyShortNameTitle = j.name;
						break;
					}
				}
			}
		} else {
			dataList.value = [];
		}
		paging.value.complete(dataList.value);
	};

	/**
	* 拉取车辆类型
	*/
	const getCarTypeList = async () => {
		const _carTypeList = await CfCarParkUtil.getCarTypeListByQuery({
			page: 1,
			size: 100
		});
		if (_carTypeList.code == 10002) {
			carTypeList.value = _carTypeList.data;
      for (const i of _carTypeList.data) {
        selectOptions.value.carTypeLabel[i.flagKey] = i.name;
        selectOptions.value.dict.carTypeList.push({
          label: i.name,
          text: i.name,
          value: i.flagKey
        });
      }
		} else {
			carTypeList.value = [];
		}
	};

	/**
	* 拉取支付方式
	*/
	const getPaymentAgencyList = async () => {
		const _paymentAgencyList = await CfPayUtil.getPaymentAgencyListByQuery({
			page: 1,
			size: 200
		})
		if (_paymentAgencyList.code == 10002) {
			paymentAgencyList.value = _paymentAgencyList.data;

		} else {
			paymentAgencyList.value = [];
		}
	}
  /**
   * 拉取出入口通道
   */
  const getCheckPointList = async () => {
    const _checkPointList = await CfIOTUtil.getCheckPointListByQuery({
      page: 1,
      size: 200,
      areaId: carParkId.value
    })
    if (_checkPointList.code == 10002) {
      for (const i of _checkPointList.data) {
        selectOptions.value.checkPointLabel[i.id] = i.name;
        if(i.features==='in'){
          selectOptions.value.dict.inCheckPointList.push({
            label: i.name,
            text: i.name,
            value: i.id
          });
        }else{
          selectOptions.value.dict.outCheckPointList.push({
            label: i.name,
            text: i.name,
            value: i.id
          });
        }
      }
    }
  }

	/**
	* 根据车辆类型key获取名称
	* @param key
	*/
	const getCarTypeName = (key : string) => {
		// @ts-ignore
		const findRes : any = carTypeList.value.find((i) => i.flagKey === key);
		return findRes?.name;
	};
	onMounted(() => { });
	onLoad((params) => {
		getCarTypeList();
		getPaymentAgencyList();
		if (params != undefined) {
			carParkId.value = params.id;
      getCheckPointList();
		}
	});
</script>

<style lang="scss" scoped>
	.dropdown-menu {
		position: relative;
		width: 100%;
		margin-top: 500rpx;
		display: flex;
		align-items: center;
		justify-content: space-around;

		.dropdown-menu-item {
			flex: 1;
			background-color: var(--tn-color-gray-light);
			padding: 20rpx 0rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			&+.dropdown-menu-item {
				margin-left: 16rpx;
			}
		}
	}

	.dropdown-content {
		position: relative;
		width: 100%;
		height: 500rpx;
		background-color: var(--tn-color-white);
	}

	.list-item {
		display: flex;
		align-items: center;
		/* 列表项之间的间距 */
		// padding: 10px 0; /* 增加上下内边距以增加高度 */
		// border-bottom: 1px solid rgba(151, 150, 150, 0.3); /* 添加底部边框线 */
		background-color: #fff;
		/* 确保背景颜色与原样式一致 */

		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		/* 阴影 */
	}

	.parking-name {
		flex: 1;
		/* 使停车场名称占据剩余空间 */
	}

</style>
